home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2002 November / SGI IRIX Base Documentation 2002 November.iso / usr / share / catman / u_man / cat1 / perlref.z / perlref
Encoding:
Text File  |  2002-10-03  |  31.4 KB  |  859 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlref - Perl references and nested data structures
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      Before release 5 of Perl it was difficult to represent complex data
  13.      structures, because all references had to be symbolic--and even then it
  14.      was difficult to refer to a variable instead of a symbol table entry.
  15.      Perl now not only makes it easier to use symbolic references to
  16.      variables, but also lets you have "hard" references to any piece of data
  17.      or code.  Any scalar may hold a hard reference.  Because arrays and
  18.      hashes contain scalars, you can now easily build arrays of arrays, arrays
  19.      of hashes, hashes of arrays, arrays of hashes of functions, and so on.
  20.  
  21.      Hard references are smart--they keep track of reference counts for you,
  22.      automatically freeing the thing referred to when its reference count goes
  23.      to zero.  (Note: the reference counts for values in self-referential or
  24.      cyclic data structures may not go to zero without a little help; see the
  25.      section on _T_w_o-_P_h_a_s_e_d _G_a_r_b_a_g_e _C_o_l_l_e_c_t_i_o_n in the _p_e_r_l_o_b_j manpage for a
  26.      detailed explanation.)  If that thing happens to be an object, the object
  27.      is destructed.  See the _p_e_r_l_o_b_j manpage for more about objects.  (In a
  28.      sense, everything in Perl is an object, but we usually reserve the word
  29.      for references to objects that have been officially "blessed" into a
  30.      class package.)
  31.  
  32.      Symbolic references are names of variables or other objects, just as a
  33.      symbolic link in a Unix filesystem contains merely the name of a file.
  34.      The *glob notation is a kind of symbolic reference.  (Symbolic references
  35.      are sometimes called "soft references", but please don't call them that;
  36.      references are confusing enough without useless synonyms.)
  37.  
  38.      In contrast, hard references are more like hard links in a Unix file
  39.      system: They are used to access an underlying object without concern for
  40.      what its (other) name is.  When the word "reference" is used without an
  41.      adjective, as in the following paragraph, it is usually talking about a
  42.      hard reference.
  43.  
  44.      References are easy to use in Perl.  There is just one overriding
  45.      principle: Perl does no implicit referencing or dereferencing.  When a
  46.      scalar is holding a reference, it always behaves as a simple scalar.  It
  47.      doesn't magically start being an array or hash or subroutine; you have to
  48.      tell it explicitly to do so, by dereferencing it.
  49.  
  50.      MMMMaaaakkkkiiiinnnngggg RRRReeeeffffeeeerrrreeeennnncccceeeessss
  51.  
  52.      References can be created in several ways.
  53.  
  54.      1.  By using the backslash operator on a variable, subroutine, or value.
  55.          (This works much like the & (address-of) operator in C.)  Note that
  56.          this typically creates _A_N_O_T_H_E_R reference to a variable, because
  57.          there's already a reference to the variable in the symbol table.  But
  58.          the symbol table reference might go away, and you'll still have the
  59.          reference that the backslash returned.  Here are some examples:
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  71.  
  72.  
  73.  
  74.              $scalarref = \$foo;
  75.              $arrayref  = \@ARGV;
  76.              $hashref   = \%ENV;
  77.              $coderef   = \&handler;
  78.              $globref   = \*foo;
  79.  
  80.          It isn't possible to create a true reference to an IO handle
  81.          (filehandle or dirhandle) using the backslash operator.  The most you
  82.          can get is a reference to a typeglob, which is actually a complete
  83.          symbol table entry.  But see the explanation of the *foo{THING}
  84.          syntax below.  However, you can still use type globs and globrefs as
  85.          though they were IO handles.
  86.  
  87.      2.  A reference to an anonymous array can be created using square
  88.          brackets:
  89.  
  90.              $arrayref = [1, 2, ['a', 'b', 'c']];
  91.  
  92.          Here we've created a reference to an anonymous array of three
  93.          elements whose final element is itself a reference to another
  94.          anonymous array of three elements.  (The multidimensional syntax
  95.          described later can be used to access this.  For example, after the
  96.          above, $arrayref->[2][1] would have the value "b".)
  97.  
  98.          Note that taking a reference to an enumerated list is not the same as
  99.          using square brackets--instead it's the same as creating a list of
  100.          references!
  101.  
  102.              @list = (\$a, \@b, \%c);
  103.              @list = \($a, @b, %c);      # same thing!
  104.  
  105.          As a special case, \(@foo) returns a list of references to the
  106.          contents of @foo, not a reference to @foo itself.  Likewise for %foo.
  107.  
  108.      3.  A reference to an anonymous hash can be created using curly brackets:
  109.  
  110.              $hashref = {
  111.                  'Adam'  => 'Eve',
  112.                  'Clyde' => 'Bonnie',
  113.              };
  114.  
  115.          Anonymous hash and array composers like these can be intermixed
  116.          freely to produce as complicated a structure as you want.  The
  117.          multidimensional syntax described below works for these too.  The
  118.          values above are literals, but variables and expressions would work
  119.          just as well, because assignment operators in Perl (even within
  120.          _l_o_c_a_l() or _m_y()) are executable statements, not compile-time
  121.          declarations.
  122.  
  123.          Because curly brackets (braces) are used for several other things
  124.          including BLOCKs, you may occasionally have to disambiguate braces at
  125.          the beginning of a statement by putting a + or a return in front so
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  137.  
  138.  
  139.  
  140.          that Perl realizes the opening brace isn't starting a BLOCK.  The
  141.          economy and mnemonic value of using curlies is deemed worth this
  142.          occasional extra hassle.
  143.  
  144.          For example, if you wanted a function to make a new hash and return a
  145.          reference to it, you have these options:
  146.  
  147.              sub hashem {        { @_ } }   # silently wrong
  148.              sub hashem {       +{ @_ } }   # ok
  149.              sub hashem { return { @_ } }   # ok
  150.  
  151.          On the other hand, if you want the other meaning, you can do this:
  152.  
  153.              sub showem {        { @_ } }   # ambiguous (currently ok, but may change)
  154.              sub showem {       {; @_ } }   # ok
  155.              sub showem { { return @_ } }   # ok
  156.  
  157.          Note how the leading +{ and {; always serve to disambiguate the
  158.          expression to mean either the HASH reference, or the BLOCK.
  159.  
  160.      4.  A reference to an anonymous subroutine can be created by using sub
  161.          without a subname:
  162.  
  163.              $coderef = sub { print "Boink!\n" };
  164.  
  165.          Note the presence of the semicolon.  Except for the fact that the
  166.          code inside isn't executed immediately, a sub {} is not so much a
  167.          declaration as it is an operator, like do{} or eval{}.  (However, no
  168.          matter how many times you execute that particular line (unless you're
  169.          in an eval("...")), $coderef will still have a reference to the _S_A_M_E
  170.          anonymous subroutine.)
  171.  
  172.          Anonymous subroutines act as closures with respect to _m_y() variables,
  173.          that is, variables visible lexically within the current scope.
  174.          Closure is a notion out of the Lisp world that says if you define an
  175.          anonymous function in a particular lexical context, it pretends to
  176.          run in that context even when it's called outside of the context.
  177.  
  178.          In human terms, it's a funny way of passing arguments to a subroutine
  179.          when you define it as well as when you call it.  It's useful for
  180.          setting up little bits of code to run later, such as callbacks.  You
  181.          can even do object-oriented stuff with it, though Perl already
  182.          provides a different mechanism to do that--see the _p_e_r_l_o_b_j manpage.
  183.  
  184.          You can also think of closure as a way to write a subroutine template
  185.          without using eval.  (In fact, in version 5.000, eval was the _o_n_l_y
  186.          way to get closures.  You may wish to use "require 5.001" if you use
  187.          closures.)
  188.  
  189.          Here's a small example of how closures works:
  190.  
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  203.  
  204.  
  205.  
  206.              sub newprint {
  207.                  my $x = shift;
  208.                  return sub { my $y = shift; print "$x, $y!\n"; };
  209.              }
  210.              $h = newprint("Howdy");
  211.              $g = newprint("Greetings");
  212.  
  213.              # Time passes...
  214.  
  215.              &$h("world");
  216.              &$g("earthlings");
  217.  
  218.          This prints
  219.  
  220.              Howdy, world!
  221.              Greetings, earthlings!
  222.  
  223.          Note particularly that $x continues to refer to the value passed into
  224.          _n_e_w_p_r_i_n_t() _d_e_s_p_i_t_e the fact that the "my $x" has seemingly gone out
  225.          of scope by the time the anonymous subroutine runs.  That's what
  226.          closure is all about.
  227.  
  228.          This applies only to lexical variables, by the way.  Dynamic
  229.          variables continue to work as they have always worked.  Closure is
  230.          not something that most Perl programmers need trouble themselves
  231.          about to begin with.
  232.  
  233.      5.  References are often returned by special subroutines called
  234.          constructors.  Perl objects are just references to a special kind of
  235.          object that happens to know which package it's associated with.
  236.          Constructors are just special subroutines that know how to create
  237.          that association.  They do so by starting with an ordinary reference,
  238.          and it remains an ordinary reference even while it's also being an
  239.          object.  Constructors are often named _n_e_w() and called indirectly:
  240.  
  241.              $objref = new Doggie (Tail => 'short', Ears => 'long');
  242.  
  243.          But don't have to be:
  244.  
  245.              $objref   = Doggie->new(Tail => 'short', Ears => 'long');
  246.  
  247.              use Term::Cap;
  248.              $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
  249.  
  250.              use Tk;
  251.              $main    = MainWindow->new();
  252.              $menubar = $main->Frame(-relief              => "raised",
  253.                                      -borderwidth         => 2)
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  269.  
  270.  
  271.  
  272.      6.  References of the appropriate type can spring into existence if you
  273.          dereference them in a context that assumes they exist.  Because we
  274.          haven't talked about dereferencing yet, we can't show you any
  275.          examples yet.
  276.  
  277.      7.  A reference can be created by using a special syntax, lovingly known
  278.          as the *foo{THING} syntax.  *foo{THING} returns a reference to the
  279.          THING slot in *foo (which is the symbol table entry which holds
  280.          everything known as foo).
  281.  
  282.              $scalarref = *foo{SCALAR};
  283.              $arrayref  = *ARGV{ARRAY};
  284.              $hashref   = *ENV{HASH};
  285.              $coderef   = *handler{CODE};
  286.              $ioref     = *STDIN{IO};
  287.              $globref   = *foo{GLOB};
  288.  
  289.          All of these are self-explanatory except for *foo{IO}.  It returns
  290.          the IO handle, used for file handles (the open entry in the _p_e_r_l_f_u_n_c
  291.          manpage), sockets (the socket entry in the _p_e_r_l_f_u_n_c manpage and the
  292.          socketpair entry in the _p_e_r_l_f_u_n_c manpage), and directory handles (the
  293.          opendir entry in the _p_e_r_l_f_u_n_c manpage).  For compatibility with
  294.          previous versions of Perl, *foo{FILEHANDLE} is a synonym for
  295.          *foo{IO}.
  296.  
  297.          *foo{THING} returns undef if that particular THING hasn't been used
  298.          yet, except in the case of scalars.  *foo{SCALAR} returns a reference
  299.          to an anonymous scalar if $foo hasn't been used yet.  This might
  300.          change in a future release.
  301.  
  302.          *foo{IO} is an alternative to the \*HANDLE mechanism given in the
  303.          section on _T_y_p_e_g_l_o_b_s _a_n_d _F_i_l_e_h_a_n_d_l_e_s in the _p_e_r_l_d_a_t_a manpage for
  304.          passing filehandles into or out of subroutines, or storing into
  305.          larger data structures.  Its disadvantage is that it won't create a
  306.          new filehandle for you.  Its advantage is that you have no risk of
  307.          clobbering more than you want to with a typeglob assignment, although
  308.          if you assign to a scalar instead of a typeglob, you're ok.
  309.  
  310.              splutter(*STDOUT);
  311.              splutter(*STDOUT{IO});
  312.  
  313.              sub splutter {
  314.                  my $fh = shift;
  315.                  print $fh "her um well a hmmm\n";
  316.              }
  317.  
  318.              $rec = get_rec(*STDIN);
  319.              $rec = get_rec(*STDIN{IO});
  320.  
  321.  
  322.  
  323.  
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  335.  
  336.  
  337.  
  338.              sub get_rec {
  339.                  my $fh = shift;
  340.                  return scalar <$fh>;
  341.              }
  342.  
  343.  
  344.      UUUUssssiiiinnnngggg RRRReeeeffffeeeerrrreeeennnncccceeeessss
  345.  
  346.      That's it for creating references.  By now you're probably dying to know
  347.      how to use references to get back to your long-lost data.  There are
  348.      several basic methods.
  349.  
  350.      1.  Anywhere you'd put an identifier (or chain of identifiers) as part of
  351.          a variable or subroutine name, you can replace the identifier with a
  352.          simple scalar variable containing a reference of the correct type:
  353.  
  354.              $bar = $$scalarref;
  355.              push(@$arrayref, $filename);
  356.              $$arrayref[0] = "January";
  357.              $$hashref{"KEY"} = "VALUE";
  358.              &$coderef(1,2,3);
  359.              print $globref "output\n";
  360.  
  361.          It's important to understand that we are specifically _N_O_T
  362.          dereferencing $arrayref[0] or $hashref{"KEY"} there.  The dereference
  363.          of the scalar variable happens _B_E_F_O_R_E it does any key lookups.
  364.          Anything more complicated than a simple scalar variable must use
  365.          methods 2 or 3 below.  However, a "simple scalar" includes an
  366.          identifier that itself uses method 1 recursively.  Therefore, the
  367.          following prints "howdy".
  368.  
  369.              $refrefref = \\\"howdy";
  370.              print $$$$refrefref;
  371.  
  372.  
  373.      2.  Anywhere you'd put an identifier (or chain of identifiers) as part of
  374.          a variable or subroutine name, you can replace the identifier with a
  375.          BLOCK returning a reference of the correct type.  In other words, the
  376.          previous examples could be written like this:
  377.  
  378.              $bar = ${$scalarref};
  379.              push(@{$arrayref}, $filename);
  380.              ${$arrayref}[0] = "January";
  381.              ${$hashref}{"KEY"} = "VALUE";
  382.              &{$coderef}(1,2,3);
  383.              $globref->print("output\n");  # iff IO::Handle is loaded
  384.  
  385.          Admittedly, it's a little silly to use the curlies in this case, but
  386.          the BLOCK can contain any arbitrary expression, in particular,
  387.          subscripted expressions:
  388.  
  389.              &{ $dispatch{$index} }(1,2,3);      # call correct routine
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  401.  
  402.  
  403.  
  404.          Because of being able to omit the curlies for the simple case of $$x,
  405.          people often make the mistake of viewing the dereferencing symbols as
  406.          proper operators, and wonder about their precedence.  If they were,
  407.          though, you could use parentheses instead of braces.  That's not the
  408.          case.  Consider the difference below; case 0 is a short-hand version
  409.          of case 1, _N_O_T case 2:
  410.  
  411.              $$hashref{"KEY"}   = "VALUE";       # CASE 0
  412.              ${$hashref}{"KEY"} = "VALUE";       # CASE 1
  413.              ${$hashref{"KEY"}} = "VALUE";       # CASE 2
  414.              ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
  415.  
  416.          Case 2 is also deceptive in that you're accessing a variable called
  417.          %hashref, not dereferencing through $hashref to the hash it's
  418.          presumably referencing.  That would be case 3.
  419.  
  420.      3.  Subroutine calls and lookups of individual array elements arise often
  421.          enough that it gets cumbersome to use method 2.  As a form of
  422.          syntactic sugar, the examples for method 2 may be written:
  423.  
  424.              $arrayref->[0] = "January";   # Array element
  425.              $hashref->{"KEY"} = "VALUE";  # Hash element
  426.              $coderef->(1,2,3);            # Subroutine call
  427.  
  428.          The left side of the arrow can be any expression returning a
  429.          reference, including a previous dereference.  Note that $array[$x] is
  430.          _N_O_T the same thing as $array->[$x] here:
  431.  
  432.              $array[$x]->{"foo"}->[0] = "January";
  433.  
  434.          This is one of the cases we mentioned earlier in which references
  435.          could spring into existence when in an lvalue context.  Before this
  436.          statement, $array[$x] may have been undefined.  If so, it's
  437.          automatically defined with a hash reference so that we can look up
  438.          {"foo"} in it.  Likewise $array[$x]->{"foo"} will automatically get
  439.          defined with an array reference so that we can look up [0] in it.
  440.          This process is called _a_u_t_o_v_i_v_i_f_i_c_a_t_i_o_n.
  441.  
  442.          One more thing here.  The arrow is optional _B_E_T_W_E_E_N brackets
  443.          subscripts, so you can shrink the above down to
  444.  
  445.              $array[$x]{"foo"}[0] = "January";
  446.  
  447.          Which, in the degenerate case of using only ordinary arrays, gives
  448.          you multidimensional arrays just like C's:
  449.  
  450.              $score[$x][$y][$z] += 42;
  451.  
  452.          Well, okay, not entirely like C's arrays, actually.  C doesn't know
  453.          how to grow its arrays on demand.  Perl does.
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  467.  
  468.  
  469.  
  470.      4.  If a reference happens to be a reference to an object, then there are
  471.          probably methods to access the things referred to, and you should
  472.          probably stick to those methods unless you're in the class package
  473.          that defines the object's methods.  In other words, be nice, and
  474.          don't violate the object's encapsulation without a very good reason.
  475.          Perl does not enforce encapsulation.  We are not totalitarians here.
  476.          We do expect some basic civility though.
  477.  
  478.      The _r_e_f() operator may be used to determine what type of thing the
  479.      reference is pointing to.  See the _p_e_r_l_f_u_n_c manpage.
  480.  
  481.      The _b_l_e_s_s() operator may be used to associate the object a reference
  482.      points to with a package functioning as an object class.  See the _p_e_r_l_o_b_j
  483.      manpage.
  484.  
  485.      A typeglob may be dereferenced the same way a reference can, because the
  486.      dereference syntax always indicates the kind of reference desired.  So
  487.      ${*foo} and ${\$foo} both indicate the same scalar variable.
  488.  
  489.      Here's a trick for interpolating a subroutine call into a string:
  490.  
  491.          print "My sub returned @{[mysub(1,2,3)]} that time.\n";
  492.  
  493.      The way it works is that when the @{...} is seen in the double-quoted
  494.      string, it's evaluated as a block.  The block creates a reference to an
  495.      anonymous array containing the results of the call to mysub(1,2,3).  So
  496.      the whole block returns a reference to an array, which is then
  497.      dereferenced by @{...} and stuck into the double-quoted string. This
  498.      chicanery is also useful for arbitrary expressions:
  499.  
  500.          print "That yields @{[$n + 5]} widgets\n";
  501.  
  502.  
  503.      SSSSyyyymmmmbbbboooolllliiiicccc rrrreeeeffffeeeerrrreeeennnncccceeeessss
  504.  
  505.      We said that references spring into existence as necessary if they are
  506.      undefined, but we didn't say what happens if a value used as a reference
  507.      is already defined, but _I_S_N'_T a hard reference.  If you use it as a
  508.      reference in this case, it'll be treated as a symbolic reference.  That
  509.      is, the value of the scalar is taken to be the _N_A_M_E of a variable, rather
  510.      than a direct link to a (possibly) anonymous value.
  511.  
  512.      People frequently expect it to work like this.  So it does.
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  533.  
  534.  
  535.  
  536.          $name = "foo";
  537.          $$name = 1;                 # Sets $foo
  538.          ${$name} = 2;               # Sets $foo
  539.          ${$name x 2} = 3;           # Sets $foofoo
  540.          $name->[0] = 4;             # Sets $foo[0]
  541.          @$name = ();                # Clears @foo
  542.          &$name();                   # Calls &foo() (as in Perl 4)
  543.          $pack = "THAT";
  544.          ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
  545.  
  546.      This is very powerful, and slightly dangerous, in that it's possible to
  547.      intend (with the utmost sincerity) to use a hard reference, and
  548.      accidentally use a symbolic reference instead.  To protect against that,
  549.      you can say
  550.  
  551.          use strict 'refs';
  552.  
  553.      and then only hard references will be allowed for the rest of the
  554.      enclosing block.  An inner block may countermand that with
  555.  
  556.          no strict 'refs';
  557.  
  558.      Only package variables (globals, even if localized) are visible to
  559.      symbolic references.  Lexical variables (declared with _m_y()) aren't in a
  560.      symbol table, and thus are invisible to this mechanism.  For example:
  561.  
  562.          local $value = 10;
  563.          $ref = \$value;
  564.          {
  565.              my $value = 20;
  566.              print $$ref;
  567.          }
  568.  
  569.      This will still print 10, not 20.  Remember that _l_o_c_a_l() affects package
  570.      variables, which are all "global" to the package.
  571.  
  572.      NNNNooootttt----ssssoooo----ssssyyyymmmmbbbboooolllliiiicccc rrrreeeeffffeeeerrrreeeennnncccceeeessss
  573.  
  574.      A new feature contributing to readability in perl version 5.001 is that
  575.      the brackets around a symbolic reference behave more like quotes, just as
  576.      they always have within a string.  That is,
  577.  
  578.          $push = "pop on ";
  579.          print "${push}over";
  580.  
  581.      has always meant to print "pop on over", despite the fact that push is a
  582.      reserved word.  This has been generalized to work the same outside of
  583.      quotes, so that
  584.  
  585.          print ${push} . "over";
  586.  
  587.      and even
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  599.  
  600.  
  601.  
  602.          print ${ push } . "over";
  603.  
  604.      will have the same effect.  (This would have been a syntax error in Perl
  605.      5.000, though Perl 4 allowed it in the spaceless form.)  Note that this
  606.      construct is _n_o_t considered to be a symbolic reference when you're using
  607.      strict refs:
  608.  
  609.          use strict 'refs';
  610.          ${ bareword };      # Okay, means $bareword.
  611.          ${ "bareword" };    # Error, symbolic reference.
  612.  
  613.      Similarly, because of all the subscripting that is done using single
  614.      words, we've applied the same rule to any bareword that is used for
  615.      subscripting a hash.  So now, instead of writing
  616.  
  617.          $array{ "aaa" }{ "bbb" }{ "ccc" }
  618.  
  619.      you can write just
  620.  
  621.          $array{ aaa }{ bbb }{ ccc }
  622.  
  623.      and not worry about whether the subscripts are reserved words.  In the
  624.      rare event that you do wish to do something like
  625.  
  626.          $array{ shift }
  627.  
  628.      you can force interpretation as a reserved word by adding anything that
  629.      makes it more than a bareword:
  630.  
  631.          $array{ shift() }
  632.          $array{ +shift }
  633.          $array{ shift @_ }
  634.  
  635.      The ----wwww switch will warn you if it interprets a reserved word as a string.
  636.      But it will no longer warn you about using lowercase words, because the
  637.      string is effectively quoted.
  638.  
  639.      FFFFuuuunnnnccccttttiiiioooonnnn TTTTeeeemmmmppppllllaaaatttteeeessss
  640.  
  641.      As explained above, a closure is an anonymous function with access to the
  642.      lexical variables visible when that function was compiled.  It retains
  643.      access to those variables even though it doesn't get run until later,
  644.      such as in a signal handler or a Tk callback.
  645.  
  646.      Using a closure as a function template allows us to generate many
  647.      functions that act similarly.  Suppopose you wanted functions named after
  648.      the colors that generated HTML font changes for the various colors:
  649.  
  650.          print "Be ", red("careful"), "with that ", green("light");
  651.  
  652.      The _r_e_d() and _g_r_e_e_n() functions would be very similar.  To create these,
  653.      we'll assign a closure to a typeglob of the name of the function we're
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  665.  
  666.  
  667.  
  668.      trying to build.
  669.  
  670.          @colors = qw(red blue green yellow orange purple violet);
  671.          for my $name (@colors) {
  672.              no strict 'refs';       # allow symbol table manipulation
  673.              *$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
  674.          }
  675.  
  676.      Now all those different functions appear to exist independently.  You can
  677.      call _r_e_d(), _R_E_D(), _b_l_u_e(), _B_L_U_E(), _g_r_e_e_n(), etc.  This technique saves on
  678.      both compile time and memory use, and is less error-prone as well, since
  679.      syntax checks happen at compile time.  It's critical that any variables
  680.      in the anonymous subroutine be lexicals in order to create a proper
  681.      closure.  That's the reasons for the my on the loop iteration variable.
  682.  
  683.      This is one of the only places where giving a prototype to a closure
  684.      makes much sense.  If you wanted to impose scalar context on the
  685.      arguments of these functions (probably not a wise idea for this
  686.      particular example), you could have written it this way instead:
  687.  
  688.          *$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" };
  689.  
  690.      However, since prototype checking happens at compile time, the assignment
  691.      above happens too late to be of much use.  You could address this by
  692.      putting the whole loop of assignments within a BEGIN block, forcing it to
  693.      occur during compilation.
  694.  
  695.      Access to lexicals that change over type--like those in the for loop
  696.      above--only works with closures, not general subroutines.  In the general
  697.      case, then, named subroutines do not nest properly, although anonymous
  698.      ones do.  If you are accustomed to using nested subroutines in other
  699.      programming languages with their own private variables, you'll have to
  700.      work at it a bit in Perl.  The intuitive coding of this kind of thing
  701.      incurs mysterious warnings about ``will not stay shared''.  For example,
  702.      this won't work:
  703.  
  704.          sub outer {
  705.              my $x = $_[0] + 35;
  706.              sub inner { return $x * 19 }   # WRONG
  707.              return $x + inner();
  708.          }
  709.  
  710.      A work-around is the following:
  711.  
  712.          sub outer {
  713.              my $x = $_[0] + 35;
  714.              local *inner = sub { return $x * 19 };
  715.              return $x + inner();
  716.          }
  717.  
  718.      Now _i_n_n_e_r() can only be called from within _o_u_t_e_r(), because of the
  719.      temporary assignments of the closure (anonymous subroutine).  But when it
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  731.  
  732.  
  733.  
  734.      does, it has normal access to the lexical variable $x from the scope of
  735.      _o_u_t_e_r().
  736.  
  737.      This has the interesting effect of creating a function local to another
  738.      function, something not normally supported in Perl.
  739.  
  740. WWWWAAAARRRRNNNNIIIINNNNGGGG
  741.      You may not (usefully) use a reference as the key to a hash.  It will be
  742.      converted into a string:
  743.  
  744.          $x{ \$a } = $a;
  745.  
  746.      If you try to dereference the key, it won't do a hard dereference, and
  747.      you won't accomplish what you're attempting.  You might want to do
  748.      something more like
  749.  
  750.          $r = \@a;
  751.          $x{ $r } = $r;
  752.  
  753.      And then at least you can use the _v_a_l_u_e_s(), which will be real refs,
  754.      instead of the _k_e_y_s(), which won't.
  755.  
  756.      The standard Tie::RefHash module provides a convenient workaround to
  757.      this.
  758.  
  759. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  760.      Besides the obvious documents, source code can be instructive.  Some
  761.      rather pathological examples of the use of references can be found in the
  762.      _t/_o_p/_r_e_f._t regression test in the Perl source directory.
  763.  
  764.      See also the _p_e_r_l_d_s_c manpage and the _p_e_r_l_l_o_l manpage for how to use
  765.      references to create complex data structures, and the _p_e_r_l_t_o_o_t manpage,
  766.      the _p_e_r_l_o_b_j manpage, and the _p_e_r_l_b_o_t manpage for how to use them to
  767.      create objects.
  768.  
  769.  
  770.  
  771.  
  772.  
  773.  
  774.  
  775.  
  776.  
  777.  
  778.  
  779.  
  780.  
  781.  
  782.  
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))                                                          PPPPEEEERRRRLLLLRRRREEEEFFFF((((1111))))
  797.  
  798.  
  799.  
  800.  
  801.  
  802.  
  803.  
  804.  
  805.  
  806.  
  807.  
  808.  
  809.  
  810.  
  811.  
  812.  
  813.  
  814.  
  815.  
  816.  
  817.  
  818.  
  819.  
  820.  
  821.  
  822.  
  823.  
  824.  
  825.  
  826.  
  827.  
  828.  
  829.  
  830.  
  831.  
  832.  
  833.  
  834.  
  835.  
  836.  
  837.  
  838.  
  839.  
  840.  
  841.  
  842.  
  843.  
  844.  
  845.  
  846.  
  847.  
  848.  
  849.  
  850.  
  851.  
  852.                                                                        PPPPaaaaggggeeee 11113333
  853.  
  854.  
  855.  
  856.  
  857.  
  858.  
  859.